/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package objectExtraction;

import com.googlecode.javacv.cpp.opencv_calib3d.*;
import static com.googlecode.javacv.cpp.opencv_core.*;
import com.googlecode.javacv.cpp.opencv_calib3d.*;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;

/**
 *
 * @author Shanika
 */
public class BackGroundSubtractor {

    private IplImage image, bg, foreground, gray_image, gray_bg;

    public IplImage getForeGround(IplImage img) {

        gray_image = cvCreateImage(cvGetSize(img), 8, 1);
        foreground = cvCreateImage(cvGetSize(img), 8, 1);
        image = cvCreateImage(cvGetSize(img), 8, 1);

        cvCvtColor(img, gray_image, CV_BGR2GRAY); // Get gray scale image
        cvEqualizeHist(gray_image, gray_image); // Histogram Equilizer: To adjust brightness
        cvSmooth(gray_image, gray_image, CV_BLUR, 1);

        cvAbsDiff(gray_image, gray_bg, foreground); // Absolute Difference

        cvThreshold(foreground, foreground, 40, 255, CV_THRESH_BINARY); // thresholding
        //   cvAdaptiveThreshold(foreground, foreground, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 3, 0);

        IplConvKernel se = cvCreateStructuringElementEx(3, 3, 1, 1, CV_SHAPE_ELLIPSE, null); // Struncturing Element
        IplConvKernel se1 = cvCreateStructuringElementEx(7, 7, 1, 1, CV_SHAPE_ELLIPSE, null); // Struncturing Element

        //cvMorphologyEx(foreground, foreground, image, se, CV_MOP_CLOSE, 1);
        //cvMorphologyEx(foreground, foreground, image, se1, CV_MOP_OPEN, 2);
//        cvMorphologyEx(foreground, foreground, image, se, CV_MOP_GRADIENT, 1);

        return foreground;
    }

    public void setBackground(IplImage background) {

        bg = background;
        gray_bg = cvCreateImage(cvGetSize(background), 8, 1);
        cvCvtColor(bg, gray_bg, CV_BGR2GRAY); // Get gray scale image of Background
        cvEqualizeHist(gray_bg, gray_bg); // Histogram Equilizer: To adjust brightness
        cvSmooth(gray_bg, gray_bg, CV_MEDIAN, 1);
    }

    public IplImage getBackground() {
        return gray_bg;
    }
}
